package mychat.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.regex.Pattern;

import mychat.util.MessageFactory;
import mychat.util.UserFactory;
import mychat.vo.Message;
import mychat.vo.User;

public class Client {
	public static Client cl = new Client();
	private Socket socket;
	private String serverHost = "127.0.0.1";
	private int serverPort = 6666;
	private DataInputStream in;
	private DataOutputStream out;
	private Login login;
	private User user;
	private ClientFrame frame;

	public static void main(String[] args) {
		cl.login = new Login();

	}
	public void start(String str1){
		System.out.println(str1);
		Message msg=MessageFactory.getMessage(str1);
		str1=msg.getContent();
		System.out.println(str1);
		user=UserFactory.getUser(str1);
		try {
			str1 = in.readUTF();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(str1);
		frame=new ClientFrame();
	}
	
	public User getUser(){
		return user;
	}

	private void Connection() throws Exception {
		try {
			socket = new Socket(serverHost, serverPort);
			in = new DataInputStream(socket.getInputStream());
			out = new DataOutputStream(socket.getOutputStream());
		} catch (Exception e) {
			System.out.println("不能连接到用服务器！");
			throw new Exception("Connetion Error!");
		}
	}

	public String login(String user, String pass) {
		System.out.println(user + ":" + pass);
		Message msg = MessageFactory.getLoginMessage(user, pass);
		try {
			Client.cl.Connection();
			System.out.println(msg);
			out.writeUTF(msg.toString());
			String result = in.readUTF();
			//System.out.println(result);
			return result;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public void Close() {
		try {
		} catch (Exception e) {
		} finally {
			try {
				if (Client.cl.in != null)
					Client.cl.in.close();
				if (Client.cl.out != null)
					Client.cl.out.close();
				if (!Client.cl.socket.isClosed())
					Client.cl.socket.close();
			} catch (IOException e) {
			} finally {
				System.out.println("Exit");
				System.exit(0);
			}
		}

	}
}
